<template>
	<scroll-view scroll-y="true" :class="view + ' wrap ' + (isIPX?'scroll_view_X': '')" @tap="onTap"
		:scroll-into-view="toView" :refresher-enabled="true" :refresher-triggered="triggered"
		:refresher-threshold="-100" refresher-background="#FFFFFF" @refresherrefresh="getHistoryMsg"
		@refresherrestore="refresherrestore" @scroll="scrollView">
		<view class="message" v-for="item in chatMsg" :key="item.mid" :id="item.mid">
			<!-- <view class="time">
				<text class="time-text">{{ item.time }}</text>
      </view>-->
			<view class="main" :class="item.style">
				<view class="user">
					<!-- yourname：就是消息的 from -->
					<text class="user-text">{{ (item.visibleName||item.yourname) + ' ' + item.time}}</text>
				</view>
				<image class="avatar"
					:src="item.visibleImg||'https://rsyl.oss-cn-beijing.aliyuncs.com/1b315030ef4c47ba82f5a7a1d20c8c4d.png'" />
				<view class="msg">
					<image class="err" :class="(item.style == 'self' && item.isFail) ?  'show' : 'hide'"
						src="https://rsyl.oss-cn-beijing.aliyuncs.com/0a6897d7827b47da9b42ed7e46d9db7b.png" />

					<image v-if="item.style == 'self'"
						src="https://rsyl.oss-cn-beijing.aliyuncs.com/14ea116d2505456abb442fc5bc34af58.png"
						class="msg_poprightarrow" />
					<image v-if="item.style == ''"
						src="https://rsyl.oss-cn-beijing.aliyuncs.com/06075b4fa4784297885f1e0a1a6f26fa.png"
						class="msg_popleftarrow" />
					<view v-if="item.msg.type == 'img' || item.msg.type == 'video'">
						<image v-if="item.msg.type == 'img'" class="avatar" :src="item.msg.data"
							style="width:90px; height:120px; margin:2px auto;" mode="aspectFit" @tap="previewImage"
							:data-url="item.msg.data" />
						<!-- <video v-if="item.msg.type == 'video'" :src="item.msg.data" controls style="width:300rpx;"/> -->
					</view>
					<audio-msg v-if="item.msg.type == 'audio'" :msg="item"></audio-msg>
					<view v-else-if="item.msg.type == 'txt' || item.msg.type == 'emoji'">
						<view class="template" v-for="(d_item, d_index) in item.msg.data" :key="d_index">
							<text :data-msg="item" @tap="clickMsg" v-if="d_item.type == 'txt'" class="msg-text"
								style="float:left;" selectable="true">{{ d_item.data }}</text>

							<image v-if="d_item.type == 'emoji'" class="avatar"
								:src="'/static/images/faces/' + d_item.data"
								style="width:25px; height:25px; margin:0 0 2px 0; float:left;" />
						</view>
					</view>
				</view>
			</view>
		</view>
		<view v-if="toView" style="height:0;" id="txtlastpostionitem"></view>
	</scroll-view>
	<!-- <view style="height: 1px;"></view> -->
</template>


<script>
	let msgStorage = require("../msgstorage");
	let disp = require("../../../utils/broadcast");
	let LIST_STATUS = {
		SHORT: "scroll_view_change",
		NORMAL: "scroll_view"
	};
	let page = 0;
	let Index = 0;
	let curMsgMid = '';
	let isFail = false;
	import * as API_Members from "@/api/members.js";

	export default {
		data() {
			return {
				view: LIST_STATUS.NORMAL,
				toView: "",
				chatMsg: [],
				__visibility__: false,
				isIPX: false,
				triggered: false,
			};
		},
		props: {
			username: {
				type: Object,
				default: () => ({})
			}
		},

		// lifetimes
		created() {},

		beforeMount() {
			this.__visibility__ = true;
			page = 0;
			Index = 0;
		},

		moved() {},

		destroyed() {
			this.__visibility__ = false;
			msgStorage.off("newChatMsg", this.dispMsg)
		},

		mounted(event) {
			let me = this;
			if (getApp().globalData.isIPX) {
				// this.setData({
				this.isIPX = true
				// });
			}

			this.username = uni.username;
			let username = this.username;
			let myUsername = uni.getStorageSync("myUsername");
			let sessionKey = username.groupId ? username.groupId + myUsername : username.your + myUsername;
			let chatMsg = uni.getStorageSync(sessionKey) || [];
			let renderedtoArr = uni.getStorageSync("rendered_" + sessionKey);
			if (!(chatMsg && chatMsg.length > 0) && !(renderedtoArr && renderedtoArr.length > 0)) {
				sessionKey = username.groupId ? myUsername + username.groupId : myUsername + username.your;
			}
			chatMsg = uni.getStorageSync(sessionKey) || [];
			this.renderMsg(null, null, chatMsg, sessionKey, 1);
			uni.setStorageSync(sessionKey, null);
			disp.on('em.error.sendMsgErr', function(err) {
				curMsgMid = err.data.mid;
				// isFail = true;
				// return;
				console.log('发送失败了', err);
				// return;
				let msgList = me.chatMsg;
				msgList.map(item => {
					if (item.mid.substring(item.mid.length - 10) == curMsgMid.substring(curMsgMid.length -
							10)) {
						item.msg.data[0].isFail = true;
						item.isFail = true;
						// me.setData({
						me.chatMsg = msgList
						// });
					}
				});

				// if (me.curChatMsg[0].mid == curMsgMid) {
				//   me.curChatMsg[0].msg.data[0].isShow = false;
				//   me.curChatMsg[0].isShow = false;
				// }

				uni.setStorageSync("rendered_" + sessionKey, msgList);
			});
			msgStorage.on("newChatMsg", this.dispMsg);
		},

		methods: {
			scrollView() {
				this.toView = ""
			},
			normalScroll() {
				// this.setData({
				this.view = LIST_STATUS.NORMAL
				// });
			},
			dispMsg(renderableMsg, type, curChatMsg, sesskey) {
				let me = this;
				let username = this.username;
				let myUsername = uni.getStorageSync("myUsername");
				let sessionKey = username.groupId ? username.groupId + myUsername : username.your + myUsername;
				var ChatMsgs = uni.getStorageSync(sessionKey) || [];
				let renderedtoArr = uni.getStorageSync("rendered_" + sessionKey);
				if (!(ChatMsgs && ChatMsgs.length > 0) && !(renderedtoArr && renderedtoArr.length > 0)) {
					sessionKey = username.groupId ? myUsername + username.groupId : myUsername + username.your;
				}
				me.curChatMsg = curChatMsg;

				if (!me.__visibility__) return; // 判断是否属于当前会话

				if (username.groupId) {
					// 群消息的 to 是 id，from 是 name
					if (renderableMsg.info.from == username.groupId || renderableMsg.info.to == username.groupId) {
						if (sesskey == sessionKey) {
							me.renderMsg(renderableMsg, type, curChatMsg, sessionKey, 'newMsg');
						}
					}
				} else if (renderableMsg.info.from == username.your || renderableMsg.info.to == username.your) {
					if (sesskey == sessionKey) {
						me.renderMsg(renderableMsg, type, curChatMsg, sessionKey, 'newMsg');
					}
				}
			},
			shortScroll() {
				// this.setData({
				this.view = LIST_STATUS.SHORT
				// });
			},

			onTap() {
				this.$emit("msglistTap", null, {
					bubbles: true
				});
			},

			previewImage(event) {
				var url = event.target.dataset.url;
				uni.previewImage({
					urls: [url] // 需要预览的图片 http 链接列表

				});
			},
			refresherrestore() {
				this.triggered = false; // 需要重置
			},
			getHistoryMsg() {
				console.log(321654)
				let me = this;
				let username = this.username;
				let myUsername = uni.getStorageSync("myUsername");
				let sessionKey = username.groupId ? username.groupId + myUsername : username.your + myUsername;
				let historyChatMsgs = uni.getStorageSync("rendered_" + sessionKey) || [];
				if (!(historyChatMsgs && historyChatMsgs.length > 0)) {
					sessionKey = username.groupId ? myUsername + username.groupId : myUsername + username.your;
					historyChatMsgs = uni.getStorageSync("rendered_" + sessionKey) || [];
				}
				if (Index < historyChatMsgs.length) {
					let timesMsgList = historyChatMsgs.slice(-Index - 10, -Index);
					// this.setData({
					let chatMsg = timesMsgList.concat(me.chatMsg)
					// this.toView = timesMsgList[timesMsgList.length - 1].mid
					this.toView = "txtlastpostionitem"
					// });
					Index += timesMsgList.length;

					if (timesMsgList.length == 10) {
						page++;
					}
					this.getArrName(chatMsg)
					// uni.stopPullDownRefresh();
				} else {
					this.triggered = true;
					this.$nextTick(() => {
						this.triggered = false;
					});
				}
			},

			renderMsg(renderableMsg, type, curChatMsg, sessionKey, isnew, refreshStatus) {
				let me = this;
				var historyChatMsgs = uni.getStorageSync("rendered_" + sessionKey) || [];

				historyChatMsgs = historyChatMsgs.concat(curChatMsg);
				if (!historyChatMsgs.length) return;
				let chatMsg1 = [...this.chatMsg]
				if (isnew == 'newMsg') {
					// this.setData({
					chatMsg1 = chatMsg1.concat(curChatMsg)
				this.getArrName(chatMsg1, refreshStatus)
					// 跳到最后一条
					// this.toView = historyChatMsgs[historyChatMsgs.length - 1].mid
					// this.toView = "txtlastpostionitem"
					console.log(this.toView, 222)
					// });
				} else {
					// this.setData({
					chatMsg1 = historyChatMsgs.slice(-10)

				this.getArrName(chatMsg1, refreshStatus)
					// 跳到最后一条
					// this.toView = historyChatMsgs[historyChatMsgs.length - 1].mid
					// this.toView = "txtlastpostionitem"
					console.log(this.toView, 333)
					// });
				}

				uni.setStorageSync("rendered_" + sessionKey, historyChatMsgs);
				let chatMsg = uni.getStorageSync(sessionKey) || [];
				chatMsg.map(function(item, index) {
					curChatMsg.map(function(item2, index2) {
						if (item2.mid == item.mid) {
							chatMsg.splice(index, 1);
						}
					});
				});
				uni.setStorageSync(sessionKey, chatMsg);
				Index = historyChatMsgs.slice(-10).length;
				// setTimeout 兼容支付宝小程序
				setTimeout(() => {
					uni.pageScrollTo({
						scrollTop: 5000,
						duration: 300,
						fail: (e) => {
							//console.log('滚失败了', e)
						}
					});
				}, 100)

				if (isFail) {
					this.renderFail(sessionKey);
				}
			},
			getArrName(chatMsg, refreshStatus) {
				API_Members.getUserInfoById({
					memberIds: chatMsg.map(item => item.info.from).toString()
				}).then(res => {
					if (res.data.success && res.data.result && res.data.result.length > 0) {
						chatMsg.forEach(item => {
							let Obj = res.data.result.find(ele => ele.id == item.info.from)
							if (Obj) {
								uni.getStorageInfo({
									success: (res1) => {
										let storageKeys = res1.keys;
										let key = storageKeys.find(key => key.indexOf(item
											.info.from) >= 0 && key.indexOf(
											"rendered_") < 0)
										if (key) {
											if (key.indexOf(item.info.from) == 0) {
												this.$set(item, "visibleName", Obj.nickName)
												this.$set(item, "visibleImg", Obj.face)
											} else {
												if (Obj.storeId) {
													this.$set(item, "visibleName", Obj
														.storeName)
													this.$set(item, "visibleImg", Obj
														.storeLogo)
												} else {
													this.$set(item, "visibleName", Obj
														.nickName)
													this.$set(item, "visibleImg", Obj.face)
												}
											}
										}
									}
								})
							}
						})

						setTimeout(() => {
							this.chatMsg = [...chatMsg]
							this.toView = "txtlastpostionitem"
						}, 0)
					}
					if (!refreshStatus) {
						this.triggered = true;
						this.$nextTick(() => {
							this.triggered = false;
						});
					}
				})
			},
			renderFail(sessionKey) {
				let me = this;
				let msgList = me.chatMsg;
				msgList.map(item => {
					if (item.mid.substring(item.mid.length - 10) == curMsgMid.substring(curMsgMid.length - 10)) {
						item.msg.data[0].isFail = true;
						item.isFail = true;
						// me.setData({
						me.chatMsg = msgList
						// });
					}
				});

				if (me.curChatMsg[0].mid == curMsgMid) {
					me.curChatMsg[0].msg.data[0].isShow = false;
					me.curChatMsg[0].isShow = false;
				}

				uni.setStorageSync("rendered_" + sessionKey, msgList);
				isFail = false;
			},

			clickMsg(event) {
				if (typeof(event.target.dataset.msg) == 'object' &&
					event.target.dataset.msg.msg.ext &&
					event.target.dataset.msg.msg.ext.msg_extension) {
					this.$emit("clickMsg", event.target.dataset.msg.msg.ext)
				}
			}

		}
	};
</script>
<style>
	@import "./msglist.css";
</style>
